package com.cn.xiaonuo.tcrfinance.payconfig.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.tcrfinance.payconfig.entity.PayChannel;
import com.cn.xiaonuo.tcrfinance.payconfig.entity.PayType;
import com.cn.xiaonuo.tcrfinance.payconfig.enums.HpcEnum;
import com.cn.xiaonuo.tcrfinance.payconfig.mapper.PayChannelMapper;
import com.cn.xiaonuo.tcrfinance.payconfig.mapper.PayTypeMapper;
import com.cn.xiaonuo.tcrfinance.payconfig.param.PayChannelParam;
import com.cn.xiaonuo.tcrfinance.payconfig.service.PayChannelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;


/**
 * @author luyangyang
 */
@Slf4j
@Service
public class PayChannelServiceImpl implements PayChannelService {


    @Autowired
    private PayChannelMapper payChannelMapper;

    @Autowired
    private PayTypeMapper payTypeMapper;

    @Autowired
    private Environment env;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public BusinessMessage pagePayChannel(PayChannelParam param) {
        BusinessMessage message = new BusinessMessage();
        Integer pageNo = param.getPageNo();
        Integer pageSize = param.getPageSize();
        if (pageNo == null || pageNo.intValue() < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize.intValue() < 1) {
            pageSize = 10;
        }
        if (ObjectUtils.isEmpty(param.getPayTypeId())) {
            message.setMessage("支付方式ID不能为空");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        PageHelper.startPage(pageNo, pageSize);
        LambdaQueryWrapper<PayChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PayChannel::getPayTypeId, param.getPayTypeId());
        wrapper.eq(PayChannel::getDeleted, HpcEnum.DELETED_OK.getCode());
        List<PayChannel> payChannels = payChannelMapper.selectList(wrapper);
        PageInfo<PayChannel> pageInfo = new PageInfo<>(payChannels);
        message.setData(pageInfo);
        message.setMessage(Status.success);
        message.setSuccess(true);
        message.setCode(Status.successCode);
        return message;
    }

    @Override
    public BusinessMessage addPayChannel(PayChannel param) {
        BusinessMessage message = new BusinessMessage();
        if (ObjectUtils.isEmpty(param.getPayTypeId())) {
            message.setMessage("使用场景不能为空");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        if (ObjectUtils.isEmpty(param.getCode())) {
            message.setMessage("支付方式不能为空");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        payChannelMapper.insert(param);
        message.setMessage(Status.success);
        message.setSuccess(true);
        message.setCode(Status.successCode);
        return message;
    }

    @Override
    public BusinessMessage updatePayChannel(PayChannel param) {
        BusinessMessage message = new BusinessMessage();
        if (ObjectUtils.isEmpty(param.getId())) {
            message.setMessage("支付渠道ID不能为空");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        try {
            PayChannel payChannel = payChannelMapper.selectById(param.getId());
            if (ObjectUtils.isNotEmpty(payChannel)) {
                payChannelMapper.updateById(param);
            }
            message.setMessage(Status.success);
            message.setSuccess(true);
            message.setCode(Status.successCode);
        } catch (Exception e) {
            message.setMessage("操作失败!");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage deletePayChannel(Integer id) {
        BusinessMessage message = new BusinessMessage();
        if (ObjectUtils.isEmpty(id)) {
            message.setMessage("支付渠道ID不能为空!");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        PayChannel payChannel = payChannelMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(payChannel)) {
            if (payChannel.getDeleted().equals(HpcEnum.DELETED.getCode())) {
                message.setMessage("改渠道已被删除，请勿重复提交!");
                message.setSuccess(false);
                message.setCode(Status.failCode);
                return message;
            }
            payChannel.setDeleted(HpcEnum.DELETED.getCode());
            payChannelMapper.updateById(payChannel);
            message.setMessage(Status.success);
            message.setSuccess(true);
            message.setCode(Status.successCode);
            return message;
        } else {
            message.setMessage(Status.fail);
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
    }

    @Override
    public BusinessMessage payChannelDetail(Integer id) {
        BusinessMessage message = new BusinessMessage();
        if (ObjectUtils.isEmpty(id)) {
            message.setMessage("支付渠道ID不能为空!");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        PayChannel payChannel = payChannelMapper.selectById(id);
        message.setData(payChannel);
        message.setMessage(Status.success);
        message.setSuccess(true);
        message.setCode(Status.successCode);
        return message;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BusinessMessage updatePayChannelState(PayChannelParam param) {
        BusinessMessage message = new BusinessMessage();
        if (ObjectUtils.isEmpty(param.getPayChannelId()) || ObjectUtils.isEmpty(param.getPayTypeId())) {
            message.setMessage("支付方式ID不能为空!");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        try {
            PayType payType = payTypeMapper.selectById(param.getPayTypeId());
            if (ObjectUtils.isNotEmpty(payType)) {

                PayChannel payChannel = payChannelMapper.selectById(param.getPayChannelId());
                if (param.getStatus().equals(HpcEnum.STATUS.getCode())) {
                    payChannel.setStatus(param.getStatus());
                    payChannelMapper.updateById(payChannel);
                    //关闭支付渠道时需关闭支付方式
                    payType.setStatus(param.getStatus());
                    payTypeMapper.updateById(payType);
                }
                if (param.getStatus().equals(HpcEnum.STATUS_OK.getCode())) {
                    LambdaQueryWrapper<PayChannel> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(PayChannel::getPayTypeId,param.getPayTypeId());
                    wrapper.eq(PayChannel::getDeleted,HpcEnum.DELETED_OK.getCode());
                    wrapper.eq(PayChannel::getStatus,HpcEnum.STATUS_OK.getCode());
                    PayChannel channel = payChannelMapper.selectOne(wrapper);
                    if (ObjectUtils.isNotEmpty(channel)){
                        message.setMessage("请关闭正在使用的渠道后重试!");
                        message.setSuccess(false);
                        message.setCode(Status.failCode);
                        return message;
                    }
                    PayChannelParam channelParam = new PayChannelParam();
                    channelParam.setPayChannelId(payChannel.getId());
                    channelParam.setStatus(param.getStatus());
                    //调用乡村振兴重新加载支付配置接口
                    String property = env.getProperty("xczx.refreshPay");
                    Map map = restTemplate.postForObject(property, channelParam, Map.class);
                    log.info("调用乡村振兴重新加载支付配置接口,返回状态{}", map);
                    if (!Convert.toInt(map.get("code")).equals(200)) {
                        throw new RuntimeException();
                    }
                    payChannel.setStatus(param.getStatus());
                    payChannelMapper.updateById(payChannel);
                }
            }
            message.setMessage(Status.success);
            message.setSuccess(true);
            message.setCode(Status.successCode);
        }catch (Exception e){
            message.setMessage(Status.fail);
            message.setSuccess(false);
            message.setCode(Status.failCode);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return message;
    }
}
